package com.huiyi.ai.server.modules.deepseekdoctor.service.impl;

import com.huiyi.ai.server.common.utils.ChatTypeEnum;
import com.huiyi.ai.server.common.utils.SSEMsgType;
import com.huiyi.ai.server.common.utils.SSEServer;
import com.huiyi.ai.server.modules.deepseekdoctor.service.ChatRecordService;
import com.huiyi.ai.server.modules.deepseekdoctor.service.MyDoctorService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MyDoctorServiceImpl implements MyDoctorService {

    @Resource
    private OllamaChatClient ollamaChatClient;

    @Resource
    private ChatRecordService chatRecordService;

    @Override
    public void doDoctorStreamV3(String userName, String message) {

        // 保存用户发送的记录到数据库
        chatRecordService.saveChatRecord(userName, message, ChatTypeEnum.USER);

        Prompt prompt = new Prompt(new UserMessage(message));
        Flux<ChatResponse> streamResponse = ollamaChatClient.stream(prompt);

        List<String> list = streamResponse.toStream().map(chatResponse -> {
            String content = chatResponse.getResult().getOutput().getContent();

            SSEServer.sendMessage(userName, content, SSEMsgType.ADD);

            log.info(content);
            return content;
        }).collect(Collectors.toList());

        SSEServer.sendMessage(userName, "GG", SSEMsgType.FINISH);

        // 保存AI回复的记录到数据库
        String htmlResult = "";
        for (String s : list) {
            htmlResult += s;
        }

        chatRecordService.saveChatRecord(userName, htmlResult, ChatTypeEnum.BOT);
    }
}
